package com.xywh.dakaqiandao.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xywh.dakaqiandao.R;
import com.xywh.dakaqiandao.di.component.DaggerQianDaoJiLuLieBiaoComponent;
import com.xywh.dakaqiandao.di.module.QianDaoJiLuLieBiaoModule;
import com.xywh.dakaqiandao.mvp.contract.QianDaoJiLuLieBiaoContract;
import com.xywh.dakaqiandao.mvp.presenter.QianDaoJiLuLieBiaoPresenter;
import com.xywh.dakaqiandao.mvp.ui.adapter.QianDaoJiLuLieBiaoAdapter;
import com.xywh.dakaqiandao.mvp.ui.entity.QianDaoJiLuLieBiao;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.picker.DatePicker;
import me.jessyan.armscomponent.commonres.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;

import static com.jess.arms.base.BaseConstants.BASE_URL;
import static com.jess.arms.base.BaseConstants.NAME_SPACE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_QIAN_DAO_JI_LU_LIE_BIAO)
public class QianDaoJiLuLieBiaoActivity extends BaseActivity<QianDaoJiLuLieBiaoPresenter> implements QianDaoJiLuLieBiaoContract.View, OnRefreshListener, OnLoadMoreListener {


    private static boolean mIsNeedDemo = true;
    protected int mPageIndex = 0;
    protected int mNum = 10;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;
    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @BindView(R.id.et_start)
    TextView etStart;
    @BindView(R.id.et_end)
    TextView etEnd;
    @BindView(R.id.btn_search)
    Button btnSearch;
    private QianDaoJiLuLieBiaoAdapter mAdapter;
    private List<QianDaoJiLuLieBiao> mDataBeanList = new ArrayList<>();
    private boolean hasMore = false;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerQianDaoJiLuLieBiaoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .qianDaoJiLuLieBiaoModule(new QianDaoJiLuLieBiaoModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_qian_dao_ji_lu_lie_biao; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_qian_dao_ji_lu_lie_biao));

        initRefreshLayout();
        initRecyclerView();
        initEmpty();

    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(true);
        mRefreshLayout.setOnLoadMoreListener(this);
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(QianDaoJiLuLieBiaoActivity.this));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, 10, Color.parseColor("#EEEEEE")));

        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new QianDaoJiLuLieBiaoAdapter(QianDaoJiLuLieBiaoActivity.this, mDataBeanList));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("AttenceYmd", mDataBeanList.get(position).getAttenceYmd());
                Utils.navigation(getContext(), RouterHub.ACTIVITY_QIAN_DAO_JI_LU, bundle);

            }
        });
    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        //getQianDaoJiLuLieBiaoList();
        mRefreshLayout.finishRefresh();
        mEmptyLayout.setVisibility(View.GONE);

    }

    @Override
    public void getQianDaoJiLuLieBiaoDataSuccess(QianDaoJiLuLieBiao entityList) {

//        if (entityList != null && entityList.getData() != null && entityList.getData().size() > 0) {
//            mDataBeanList.clear();
//            mDataBeanList.addAll(entityList.getData());
//            mAdapter.notifyDataSetChanged();
//            mEmptyLayout.setVisibility(View.GONE);
//            mRecyclerView.setVisibility(View.VISIBLE);
//        } else {
//            mEmptyLayout.setVisibility(View.VISIBLE);
//            mRecyclerView.setVisibility(View.GONE);
//        }

    }

    private void getQianDaoJiLuLieBiaoList() {
        HashMap<String, String> map = new HashMap<>();

        mPresenter.getQianDaoJiLuLieBiaoList(map);
    }

    @OnClick({R.id.et_start, R.id.et_end, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_start:
                onYearMonthDayTimePicker(etStart);
                break;
            case R.id.et_end:
                onYearMonthDayTimePicker(etEnd);
                break;
            case R.id.btn_search:
                try {
                    mPageIndex = 0;
                    hasMore = false;
                    mDataBeanList.clear();
                    mAdapter.notifyDataSetChanged();
                    mEmptyLayout.setVisibility(View.VISIBLE);
                    mRecyclerView.setVisibility(View.GONE);
                    getAttencesSingleUserbyDateRange();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    public void onYearMonthDayTimePicker(TextView view) {

        try {
            Calendar now = Calendar.getInstance();
            DatePicker picker = new DatePicker(this);
            picker.setCancelText("取消");
            picker.setSubmitText("确定");
            picker.setRangeStart(1900, 1, 1);
            picker.setRangeEnd(2500, 12, 31);
            picker.setSelectedItem(now.get(Calendar.YEAR), (now.get(Calendar.MONTH) + 1), now.get(Calendar.DAY_OF_MONTH));
            picker.setLabel("年", "月", "日");
            picker.setWeightEnable(true);
            picker.setLineColor(Color.BLACK);
            picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                @Override
                public void onDatePicked(String year, String month, String day) {
                    view.setText(year + "-" + month + "-" + day);
                }
            });
            picker.show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void getAttencesSingleUserbyDateRange() {

        String startTime = etStart.getText().toString();
        String endTime = etEnd.getText().toString();

        if (TextUtils.isEmpty(startTime)) {
            showMessage("请选择开始时间");
            return;
        }
        if (TextUtils.isEmpty(endTime)) {
            showMessage("请选择结束时间");
            return;
        }
        showLoading();


        String methodName = "GetAttencesSingleUserbyDateRange";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("identityCardNo", mSharedPreferencesHelper.getString(BaseConstants.USERNAME));
        params.put("Start", startTime);
        params.put("End", endTime);
        params.put("PageSize", String.valueOf(mNum));
        params.put("PageIndex", String.valueOf(mPageIndex));

        /**
         * 请求
         */
        soapUtil.call(BASE_URL, NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty("GetAttencesSingleUserbyDateRangeResult").toString();
                if (result != null) {
                    List<QianDaoJiLuLieBiao> entityList = new Gson().fromJson(result, new TypeToken<List<QianDaoJiLuLieBiao>>() {
                    }.getType());

                    if (entityList != null && entityList.size() > 0) {
//                        mDataBeanList.clear();
                        mDataBeanList.addAll(entityList);
                        mAdapter.notifyDataSetChanged();
                        mEmptyLayout.setVisibility(View.GONE);
                        mRecyclerView.setVisibility(View.VISIBLE);

                        if (entityList.size() == 10) {
                            hasMore = true;
                            mPageIndex = mPageIndex + 1;
                        } else {
                            hasMore = false;
                        }
                        LogUtils.debugEInfo("mPageIndex=" + mPageIndex);
                    } else {
                        if (mPageIndex == 0) {
                            mEmptyLayout.setVisibility(View.VISIBLE);
                            mRecyclerView.setVisibility(View.GONE);
                        }
                    }
                } else {
                    if (mPageIndex == 0) {
                        mEmptyLayout.setVisibility(View.VISIBLE);
                        mRecyclerView.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        });


    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);

    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if (hasMore)
            getAttencesSingleUserbyDateRange();
        mRefreshLayout.finishLoadMore();
    }
}
